import Segmented from '@/components/Segmented';
import {processColor, ScrollView, TouchableOpacity, View} from 'react-native';
import {Card, Icon, Text, useAppTheme} from 'tsun-smart-ui';
import {DatePickerMode, unitMap} from '@/enums/statistics';
import {useTranslation} from 'react-i18next';
import {useEffect, useLayoutEffect, useMemo, useState} from 'react';
import LineChart from '@/components/LineChart';
import MemoBarChart from '@/components/BarChart';
import EnergySourceBreakdown from './components/energySourceBreakdown';
import {hexWithOpacity, withCancelable} from '@/utils';
import useDatePicker from '@/hooks/useDatePicker';
import dayjs from 'dayjs';
// 新增：引入redux
import {useSelector, useDispatch} from 'react-redux';
import {RootState} from '@/store';
import {
  toggleColorVisible,
  setSelected,
  colors as colorsList,
  setColors,
} from '@/store/slices/landscapeColorsSlice';
import {deviceApi} from '@/services/api/deviceApi';
import {useNavigation} from '@react-navigation/native';
import Logo from '@/components/Logo';

export const dataMap = {
  pvPowerGen: {
    legend: {
      day: 'legend.generationPower',
      total: 'device.electricity_production',
    },
    viewData: 'device.electricity_production',
  },
  batteryPower: {
    legend: {
      day: 'legend.chargeDischargePower',
      total: 'device.charge_discharge_total',
    },
    viewData: 'device.charge_discharge_total',
  },
  loadPower: {
    legend: {
      day: 'legend.consumptionPower',
      total: 'device.electricity_consumption',
    },
    viewData: 'device.electricity_consumption',
  },
  gridPower: {
    legend: {
      day: 'legend.gridPower',
      total: 'device.grid_total',
    },
    viewData: 'device.grid_total',
  },
  soc: {
    legend: {
      total: 'legend.soc',
      day: 'legend.soc',
    },
    viewData: 'legend.soc',
  },
} as const;
const formatMap = {
  day: 'YYYY-MM-DD',
  month: 'YYYY-MM',
  year: 'YYYY',
  total: 'YYYY-MM-DD',
} as const;
const queryGenEle = withCancelable(deviceApi.getStationStatistics);

export const DatePickerStep = ({
  onPress,
  disabled,
  type,
  value: date,
  setValue: setDate,
}: {
  onPress: () => void;
  disabled?: boolean;
  type: DatePickerMode;
  value: dayjs.Dayjs;
  setValue: (value: dayjs.Dayjs) => void;
}) => {
  const theme = useAppTheme();
  const minDate = dayjs('2019-1-1');
  const leftDisabled = useMemo(() => {
    return type === 'total' || dayjs(minDate).isSame(date, type);
  }, [type, minDate, date]);

  const rightDisabled = useMemo(() => {
    return type === 'total' || dayjs().isSame(date, type);
  }, [type, date]);
  const onRightPress = () => {
    if (type === 'total') return;
    if (!dayjs().isSame(dayjs(date), type)) {
      const result = dayjs(date).add(1, type);
      setDate(result);
    }
  };
  const onLeftPress = () => {
    if (type === 'total') return;
    if (!dayjs(minDate).isSame(dayjs(date), type)) {
      const result = dayjs(date).subtract(1, type);
      setDate(result);
    }
  };
  return (
    <View
      pointerEvents={disabled ? 'none' : 'auto'}
      className="flex-row items-center mt-3 self-center gap-x-4">
      <Icon
        onPress={onLeftPress}
        size={16}
        className="p-2"
        name="to-left"
        color={
          disabled || leftDisabled
            ? theme.colors?.neutral?.disabled
            : theme.colors?.neutral?.title
        }></Icon>
      <Text onPress={onPress}>
        {type === 'total'
          ? `${dayjs().subtract(5, 'year').format('YYYY')}-${dayjs().format(
              'YYYY',
            )}`
          : date.format(formatMap[type])}
      </Text>
      <Icon
        onPress={onRightPress}
        name="to-right"
        size={16}
        className="p-2"
        color={
          disabled || rightDisabled
            ? theme.colors?.neutral?.disabled
            : theme.colors?.neutral?.title
        }></Icon>
    </View>
  );
};

const Statistics = ({stationId}: {stationId: number}) => {
  const {t} = useTranslation();
  const theme = useAppTheme();
  const navigation = useNavigation();
  // 用redux管理selected和colors
  const selected = useSelector(
    (state: RootState) => state.landscapeColors.selected,
  );
  const colors = useSelector(
    (state: RootState) => state.landscapeColors.colors,
  );
  const [dataList, setDataList] = useState<
    {
      title: string;
      value: number;
    }[]
  >([]);
  const dispatch = useDispatch();
  const currentStation = useSelector(
    (state: RootState) => state.fullScene.currentStation,
  );
  const params = useMemo(() => {
    return {
      stationId: stationId || currentStation?.id,
    };
  }, [currentStation?.id]);

  const {
    Picker: picker,
    selectedValue: value,
    setSelectedValue: setValue,
    result,
    currentUnit: currentSelected,
  } = useDatePicker(selected, queryGenEle, params);
  const chartData = useMemo(() => {
    const {viewData, ...totalData} = result ?? {};
    const originData = Object.entries(totalData);
    const xAxisLabels = originData[0]?.[1]?.map(item => item.time) ?? [];
    const values = originData.map(([_, value]) =>
      (value ?? []).map(item => +(item.value ?? 0)),
    );
    return {
      xAxisLabels,
      values,
    };
  }, [result]);
  useLayoutEffect(() => {
    const {viewData = {}} = result ?? {};
    const data = Object.entries(viewData);
    const dataList = data.map(([title]) => {
      return {
        title: t(dataMap[title as keyof typeof dataMap].viewData),
        value: viewData[title as keyof typeof viewData]!,
      };
    });
    setDataList(dataList);
    const colors = data.map(([title], index) => {
      return {
        title: t(
          dataMap[title as keyof typeof dataMap].legend[
            selected === 'day' ? 'day' : 'total'
          ],
        ),
        color: colorsList[index],
        visible: true,
      };
    });
    dispatch(setColors(colors));
  }, [result, selected]);
  const options = Object.entries(unitMap).map(([key, value]) => ({
    label: t(value),
    value: key as DatePickerMode,
  }));
  
  return (
    <ScrollView
      className="flex-1 px-4"
      contentContainerClassName="py-3"
      showsVerticalScrollIndicator={false}>
      <Card>
        <Segmented
          buttons={options}
          value={selected}
          onChange={v => dispatch(setSelected(v))}
        />
        <DatePickerStep
          disabled={currentSelected === 'total'}
          type={currentSelected}
          value={value}
          setValue={setValue}
          onPress={() => {
            picker.show();
          }}></DatePickerStep>
        <View>
          {currentSelected === 'day' ? (
            <LineChart
              leftUnit={`${t('device.power')}(kW)`}
              rightUnit={`SOC(%)`}
              yAxis={{
                left: {
                  drawAxisLine: true,
                },
                right: {
                  enabled: true,
                  drawGridLines: false,
                  drawAxisLine: true,
                },
              }}
              showFullScreen
              style={{
                aspectRatio: 2 / 1,
              }}
              scaleYEnabled={false}
              showLegend={false}
              onFullScreen={() => {
                navigation.navigate('FullScreen', {
                  stationId,
                });
              }}
              dataSetsConfig={colors.map(item => {
                const currentColor = processColor(item.color);
                return {
                  color: currentColor,
                  drawValues: false,
                  drawCircles: false,
                  fillGradient: {
                    colors: [
                      processColor(hexWithOpacity(item.color, 0)),
                      processColor(hexWithOpacity(item.color, 0.4)),
                    ],
                    orientation: 'BOTTOM_TOP',
                  },
                  visible: item.visible ?? true,
                  fillAlpha: 100,
                };
              })}
              title={colors.map(item => item.title)}
              marker={`${t('sys.app.time')}: `}
              xAxisLabels={chartData.xAxisLabels}
              chartData={chartData.values}
              highlightPerTapEnabled={colors.some(item => item.visible)}
            />
          ) : (
            <MemoBarChart
              leftUnit={`${t('device.electricity_production')}(kWh)`}
              yAxis={{
                right: {
                  enabled: false,
                },
              }}
              showFullScreen
              onFullScreen={() => {
                navigation.navigate('FullScreen', {
                  stationId,
                });
              }}
              style={{
                aspectRatio: 2 / 1,
              }}
              xAxis={{
                centerAxisLabels: colors.length > 1,
              }}
              marker={`${t('sys.app.time')}: `}
              scaleYEnabled={false}
              showLegend={false}
              dataSetsConfig={colors.map(item => {
                const currentColor = processColor(item.color);
                return {
                  color: currentColor,
                  drawValues: false,
                  visible: item.visible ?? true,
                };
              })}
              title={colors.map(item => item.title)}
              xAxisLabels={chartData.xAxisLabels}
              chartData={chartData.values}
              highlightPerTapEnabled={colors.some(item => item.visible)}
            />
          )}
        </View>
        <View className="flex-row flex-wrap gap-y-2 gap-x-3 mt-5">
          {colors.map(color => {
            return (
              <TouchableOpacity
                key={color.title}
                onPress={() => {
                  dispatch(toggleColorVisible(color.title));
                }}
                style={{
                  borderColor: !color.visible
                    ? theme.colors?.background?.disabled
                    : theme.colors?.background?.primary,
                  backgroundColor: !color.visible
                    ? theme.colors?.neutral?.white
                    : theme.colors?.background?.primary,
                }}
                className="flex-row items-center gap-x-1 py-[6] px-[10]  border rounded-2xl">
                <View
                  className=" size-2 rounded-full"
                  style={{
                    backgroundColor: color.color,
                  }}></View>
                <Text
                  variant="caption"
                  style={{
                    color: theme.colors?.neutral?.primary,
                  }}>
                  {color.title}
                </Text>
              </TouchableOpacity>
            );
          })}
        </View>
        <View className="flex-row items-center gap-2 mt-6">
          <Logo
            name="data"
            round={false}
            backgroundColor={theme.colors?.brand?.primaryLight!}
            color={theme.colors?.brand?.primary!}
          />
          <Text variant="bodyStrong">{`${t(unitMap[currentSelected])}${t(
            'data.total',
          )}`}</Text>
        </View>
        <View className="flex-row items-center  mt-5 flex-wrap gap-y-4">
          {dataList.map(item => {
            return (
              <View className="w-1/2" key={item.title}>
                <Text
                  variant="caption"
                  style={{
                    color: theme.colors?.neutral?.primary,
                  }}>
                  {item.title}
                </Text>
                <Text variant="navTitle">{item.value + 'kWh'}</Text>
              </View>
            );
          })}
        </View>
      </Card>
      {/* <Card
        title={
          <View className="flex-row items-center gap-2">
            <StatisticsIcon width={24} height={24} />
            <Text variant="bodyStrong">当日发电</Text>
          </View>
        }
        right={<Text variant="navTitle">15.5kWh</Text>}
        className="my-3">
        <EnergySourceBreakdown
          className="mt-5"
          sources={[
            {
              percentage: 14.64,
              name: '来自光伏',
              value: '6.7kWh',
              color: '#1FBBFF',
            },
            {
              percentage: 43.23,
              name: '来自电网',
              value: '6.7kWh',
              color: theme.colors?.info?.primary!,
            },
            {
              percentage: 100 - 14.64 - 43.23,
              name: '来自储能',
              value: '6.7kWh',
              color: theme.colors?.success?.primary!,
            },
          ]}
        />
      </Card>
      <Card
        title={
          <View className="flex-row items-center gap-2">
            <CostIcon width={24} height={24} />
            <Text variant="bodyStrong">当日消耗</Text>
          </View>
        }
        right={<Text variant="navTitle">10.5kWh</Text>}>
        <EnergySourceBreakdown
          className="mt-5"
          sources={[
            {
              percentage: 14.64,
              name: '来自光伏',
              value: '6.7kWh',
              color: '#1FBBFF',
            },
            {
              percentage: 43.23,
              name: '来自电网',
              value: '6.7kWh',
              color: theme.colors?.info?.primary!,
            },
            {
              percentage: 100 - 14.64 - 43.23,
              name: '来自储能',
              value: '6.7kWh',
              color: theme.colors?.success?.primary!,
            },
          ]}
        />
      </Card> */}
      {/* <Card
        className="mt-3"
        title={
          <View className="flex-row items-center gap-2">
            <DataIcon width={24} height={24} />
            <Text variant="bodyStrong">运行数据</Text>
          </View>
        }>
        <View className="flex-row items-center  mt-5">
          <View className="flex-1">
            <Text
              variant="caption"
              style={{
                color: theme.colors?.neutral?.primary,
              }}>
              累计运行天数
            </Text>
            <Text variant="navTitle">370天</Text>
          </View>
          <View className="flex-1">
            <Text
              variant="caption"
              style={{
                color: theme.colors?.neutral?.primary,
              }}>
              累计发电量
            </Text>
            <Text variant="navTitle">200kWh</Text>
          </View>
        </View>
      </Card> */}
    </ScrollView>
  );
};

export default Statistics;
